import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDictInfo } from '@/api/index'

export const useDictionaryStore = defineStore("dictionary", () => {
	// state :dictionary
	const dictionary = ref(uni.getStorageSync("dictionary") || {})

	// actions
	/**
	 获取全部字典信息
	 */
	function getDictionaryList() {
		return new Promise((resolve, reject) => {
			getDictInfo()
				.then(({ data }) => {
					dictionary.value = data;
					uni.setStorageSync("dictionary", data)
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	/**
	   * 获取对应字典label
	   *
	   * @param {LoginData}
	   * @returns
	   */
	function filterDictName(code : string, value : any) {
		const filter = dictionary.value[code];
		return filter?.find((e : any) => e.value === value?.toString())?.label || "";
	}

	/**
	 * 获取对应字典List
	 *
	 * @param {LoginData}
	 * @returns
	 */
	function filterDictList(code : string) {
		return dictionary.value[code] || [];
	}

	return {
		dictionary,
		filterDictName,
		filterDictList,
		getDictionaryList
	}
})